package com.sfx.service.impl;

import com.alibaba.fastjson.JSON;
import com.sfx.enums.AppHttpCodeEnum;
import com.sfx.exception.SystemException;
import com.sfx.utils.JwtUtil;
import com.sfx.utils.RedisCache;
import com.sfx.domain.ResponseResult;
import com.sfx.domain.entity.LoginUser;
import com.sfx.domain.entity.User;
import com.sfx.domain.vo.BlogUserLoginVo;
import com.sfx.domain.vo.UserInfoVo;
import com.sfx.service.BlogLoginService;
import com.sfx.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

import static com.sfx.constants.RedisConstants.BLOG_LOGIN_KEY;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-07-11
 * Time: 16:00
 */
@Service
@Slf4j
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 完成登陆功能
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        if(StringUtils.isAnyBlank(userName,password)) {
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME_PASSWORD);
        }
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(authenticate == null) {
            //验证失败
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }
        //验证成功
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //3.得到用户Id
        Long userId = loginUser.getUser().getId();
        //4.根据userId生成JWT
        String token = JwtUtil.createJWT(userId.toString());
        //5.保存用户信息到redis中
        redisCache.setCacheObject(BLOG_LOGIN_KEY + userId, loginUser);
        //6.返回登陆凭证+userInfo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(token,userInfoVo);
        return ResponseResult.okResult(blogUserLoginVo);
    }

    /**
     * 退出功能
     * @return
     */
    @Override
    public ResponseResult logout() {
        //1.获取当前登陆用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //2.获取userId
        Long userId = loginUser.getUser().getId();
        //3.删除redis中的用户信息
        redisCache.deleteObject(BLOG_LOGIN_KEY + userId);
        //4.返回
        return ResponseResult.okResult();
    }
}